
import random
import time

from django.http import HttpResponse
from django.shortcuts import render, redirect
import pandas as pd
import xlrd
import os
import re
import DataProcess.DataCleaning
from Create_address.AddressProcess import start_process, joint_address, return_address
from app import models
from app.models import ShopTable, MerchTable, UserTable, admin


# register
def reg(request):
    #id = request.POST.get('id')
    if request.method == 'POST':
        # Get data submitted by the user
        id = create_id()# get the suitable id according to the data of id list
        name = request.POST.get('name') #get the information from post
        password = request.POST.get('password')
        phone = request.POST.get('phone')
        address = request.POST.get('address')
        models.UserTable.objects.create(User_id=id, User_name = name, User_psw= password, User_phone = phone, User_address = address)# create a new user object and save
        # back to user login
        return redirect('/login/')
    # return the register page with form
    return render(request, 'reg.html', {"reg_id": create_id()})

# user login
def login(request):
    if request.method == 'POST':
        id = request.POST.get('id')#get the information from post
        password = request.POST.get('password')
        # print(username, password)
        if id == "" or password == "": # no input
            return render(request, 'login.html', {"error": "账号或密码不能为空，请重新登陆！"})
        if models.UserTable.objects.filter(User_id = id):# if find the id in id list
            u = models.UserTable.objects.get(User_id= id)# get the object that its id is correct
            if password == u.User_psw: # if the password is correct
                request.session['User_id'] = id # save the id into session to keep the user's login status active
                return redirect("/index") # go to the home page
            else:
                return render(request, 'login.html', {"error": "密码错误，请重新登陆！"}) #return the error
        else:
            return render(request, 'login.html', {'error': '账号不存在，请重新登陆！'})#return the error
    return render(request, 'login.html') # show the user login page

# log out
def quit(request):
    request.session.clear()# clean the id in session
    return redirect("/login/") #back to user login page

# go to home page
def index(request):
    all_laptop = models.MerchTable.objects.filter(Merch_name__contains="笔记本电脑")[200:208]# search the MerchTable name to find the "笔记本电脑"
    # Because the date of computer accessories is in the top hof the database, so we need to get the merchandise the lower. Actually, it is around 200
    all_ipad = models.MerchTable.objects.filter(Merch_tag="平板")[:10]# search the MerchTable tag to find the "笔记本电脑"
    all_phone = models.MerchTable.objects.filter(Merch_tag="手机")[:10]# search the MerchTable tag to find the "手机"
    id = request.session.get("User_id") # get the user id from session
    name = models.UserTable.objects.get(User_id = id).User_name # use id to get the user name
    for i in all_laptop : # cut up the name string to avoid the length exceeding the component layout
        i.Merch_name =i.Merch_name[:20]
    for i in all_ipad:
        i.Merch_name = i.Merch_name[:20]
    for i in all_phone:
        i.Merch_name = i.Merch_name[:20]
    if request.method == 'POST':
        search_name = request.POST.get('search_name')# get the name that user want to search from post
        Merch_data=models.MerchTable.objects.filter(Merch_name__contains=search_name) # use "__contains" to search the name
        Merch_data = Merch_data[:100] # show the first 100 result
        for i in Merch_data:
            i.Merch_name = i.Merch_name[:15] # cut up the name string to avoid the length exceeding the component layout
        Error=""
        if bool(Merch_data)==False:
            Error="未查询到结果"
        return render(request,"search.html",{"username":name,"Merch_data":Merch_data,"error":Error}) # go to search page
    return render(request, 'index.html', {"all_laptop": all_laptop,"all_ipad":all_ipad,"all_phone":all_phone, "username":name}) # home page

#go to merchandise page
def good(request):
    pk = request.GET.get('pk') # get the merch_id
    merch = models.MerchTable.objects.filter(Merch_id=pk)
    id = request.session.get("User_id") #
    name =  models.UserTable.objects.get(User_id = id).User_name
    for i in merch:
        merch = i
    if request.method == 'POST': # same as search part
        search_name = request.POST.get('phone') #
        Merch_data = models.MerchTable.objects.filter(Merch_name__contains=search_name) # use "__contains" to search the name
        for i in Merch_data:
            i.Merch_name = i.Merch_name[:15]
        Merch_data = Merch_data[: 100]
        Error = ""
        if bool(Merch_data) == False:
            Error = "未查询到结果"
        return render(request, "search.html", {"username": name, "Merch_data": Merch_data, "error": Error})
    return render(request,"good.html",{"merch":merch, "username":name}) # go to the merchandise page

# add merchandise into cart
def goshopcar(request):
    print("Start")
    uid = request.session.get("User_id") # get user id
    mid = request.GET.get('pk') #get the merchandise id
    #print(mid)

    sid_figure = models.MerchTable.objects.get(Merch_id = mid).Merch_sid_id # get the sid of Merchandise by Merch_sid
    #print("Step1")
    sid = models.ShopTable.objects.get(Shop_id=sid_figure).Shop_id # get the ShopTable object by sid
    #print(sid)
    try:
        previous_record = models.CartTable.objects.get(Cert_mid_id=mid, Cert_sid_id=sid) # get the all record of user
        previous_record.Cert_amount += 1 # add the amount
        previous_record.save() # save the data
        return redirect("/shopcar/")
    except models.CartTable.DoesNotExist:# if not exist
        #print("None")
        models.CartTable.objects.create(Cert_mid_id=mid, Cert_sid_id=sid, Cert_uid_id=uid, Cert_amount=1)# create a new cart record use above information
        #print("Done")

    return redirect("/shopcar/") #go to shop page

#go to cart page
def shopcar(request):
    id = request.session.get("User_id")# get user id
    #print(id)
    # name = models.UserTable.objects.get(User_id=id).User_name
    CartTable_data=models.CartTable.objects.filter(Cert_uid = id)# search the cart record by user id
    Merch_data=[]
    for i in CartTable_data:
        merch = models.MerchTable.objects.get(Merch_id=i.Cert_mid_id)# get the merchandise object
        merch.Merch_name = merch.Merch_name[:30] # set the return name
        merch.amount = i.Cert_amount #set the return amount
        Merch_data.append(merch)
        merch.total_price = int(float(merch.Merch_price))*(merch.amount)# calculate the total price of each merchandise
        # Merch_data.append(i.Cert_mid)
        # print(i.Cert_mid_id)
    sum=0
    for i in Merch_data:
        sum += int(float(i.Merch_price))*(i.amount) # calculate the total price

    return render(request,"shopcar.html",{"product":Merch_data,"all_price":sum}) # return the list of cart and total price

#delete the cart item
def delfav(request):
    pk = request.GET.get('pk')
    models.CartTable.objects.filter(Cert_mid_id=pk).delete()# delete the chosen merchandise
    return redirect("/shopcar/") # refresh cart page


#create the order
def result(request):
    id = request.session.get("User_id")# get the user id
    name = models.UserTable.objects.get(User_id=id).User_name
    CartTable_data=models.CartTable.objects.filter(Cert_uid_id=id)# cart data of user
    #print("Start 0")
    for i in CartTable_data:
        #print("Start 1")
        merch = models.MerchTable.objects.get(Merch_id=i.Cert_mid_id)# use mid of CartTable to get the merchandise

        oid = create_order_id()# create a new order id
        date = time.localtime(time.time())# get the current date
        amount = i.Cert_amount# get the amount in cart
        mid = merch.Merch_id# get the merch id
        #print("Start 2")
        #print(mid)

        sid_figure = models.MerchTable.objects.get(Merch_id=mid).Merch_sid_id# get the shop id
        sid = models.ShopTable.objects.get(Shop_id=sid_figure).Shop_id
        uid = id
        models.OrderTable.objects.create(Order_id=oid, Order_date=date, Order_amount=amount, Order_mid=models.MerchTable.objects.get(Merch_id=mid), Order_sid=models.ShopTable.objects.get(Shop_id=sid_figure), Order_uid=models.UserTable.objects.get(User_id=id))
        #create a new order item
    models.CartTable.objects.filter(Cert_uid_id=id).delete()# delete the used cart record
    if request.method == 'POST':# search part
        search_name = request.POST.get('phone')
        Merch_data = models.MerchTable.objects.filter(Merch_name__contains=search_name)
        Merch_data = Merch_data[: 100]
        for i in Merch_data:
            i.Merch_name = i.Merch_name[:15]
        Error = ""
        if bool(Merch_data) == False:
            Error = "未查询到结果"
        return render(request, "search.html", {"username": name, "Merch_data": Merch_data, "error": Error})
    return render(request,"jiesuan.html")# go to the jiesuan page
# user order page
def myorder(request):
    id = request.session.get("User_id")
    order_data=models.OrderTable.objects.filter(Order_uid=id) # use user id to get the order of user by uid foreign key
    for i in order_data:# edit the retun information
        i.order_id = i.Order_id
        i.order_img = models.MerchTable.objects.get(Merch_id=i.Order_mid_id).Merch_img
        i.order_name = models.MerchTable.objects.get(Merch_id=i.Order_mid_id).Merch_name[:15]
        i.order_price = models.MerchTable.objects.get(Merch_id=i.Order_mid_id).Merch_price
        i.order_date = i.Order_date
        i.order_amount = i.Order_amount
        i.from_address = models.ShopTable.objects.get(Shop_id=i.Order_sid_id).Shop_address
        i.to_address = models.UserTable.objects.get(User_id=i.Order_uid_id).User_address

    name = models.UserTable.objects.get(User_id=id).User_name# user name
    if request.method == 'POST':#search page
        search_name = request.POST.get('phone')
        Merch_data = models.MerchTable.objects.filter(Merch_name__contains=search_name)
        Merch_data = Merch_data[: 100]
        for i in Merch_data:
            i.Merch_name = i.Merch_name[:15]
        Error = ""
        if bool(Merch_data) == False:
            Error = "未查询到结果"
        return render(request, "search.html", {"username": name, "Merch_data": Merch_data, "error": Error})
    return render(request,"myorder.html",{"username":name,"order_data":order_data})#go to myorder page and return to order information

#search page
def search(request):
    id = request.session.get("User_id")
    name = models.UserTable.objects.get(User_id=id).User_name
    #pk = request.GET.get('pk')
    search_name = request.POST.get('search_name')
    print(search_name)
    if request.method == 'POST':#search
        search_name= request.POST.get('search_name')
        Merch_data=models.MerchTable.objects.filter(Merch_name__contains=search_name)
        Merch_data = Merch_data[:200:-1]
        Error=""
        if bool(Merch_data)==False:
            Error="未查询到结果"
        return render(request,"search.html",{"username":name,"merch_data":Merch_data,"error":Error})
    return render(request,"search.html",{"username":name})# go to search page

#admin login
def adminlogin(request):
    if request.method=="POST":
        adminuser=request.POST.get("adminuser")# get admin user name
        adminpwd=request.POST.get("adminpwd")# get the admin password
        if models.admin.objects.filter(admin_name=adminuser):# filter the name
            admin_data=models.admin.objects.get(admin_name=adminuser)
            if adminpwd==admin_data.admin_pwd:#judge the name and password
                request.session['adminuser'] = adminuser#save the adminuser name into session
                return redirect("/product_list/")# go to show the merchandise list
            else:
                error = "密码错误"
                return render(request, "adlogin.html", {"error": error})#come back
        else:
            error="账号不存在"
            return render(request, "adlogin.html",{"error":error})#come back

    return render(request,"adlogin.html")#come back

# show the admin list
def admin_list(request):
    adminuser = request.session.get("adminuser")#
    admin_data=models.admin.objects.all()
    return render(request,"admin_list.html",{"admin_data":admin_data,"adminuser":adminuser})

#delete the admin
def admin_del(request):
    pk = request.GET.get('pk')
    models.admin.objects.filter(pk=pk).delete()
    return redirect("/admin_list/")

#edit the admin information
def admin_edit(request):
    pk = request.GET.get('pk')
    admin_data = models.admin.objects.get(pk=pk)#get the name of admin that is need to edit
    if request.method=="POST":#save the new information
        admin_pwd=request.POST.get("admin_pwd")
        admin_data.admin_pwd=admin_pwd
        admin_data.save()
        return redirect("/admin_list/")
    return render(request,"admin_edit.html",{"admin_data":admin_data})#refresh
# add admin
def admin_add(request):
    if request.method=="POST":
        adusr=request.POST.get("adusr")# get the input name
        adpwd=request.POST.get("adpwd")# get the input password
        if models.admin.objects.filter(pk=adusr):#check the name and password
            error="用户名已存在！"
            return render(request,"admin_add.html",{"error":error})
        else:
            models.admin.objects.create(admin_name=adusr,admin_pwd=adpwd)#create the new admin
            return redirect("/admin_list/")
    return render(request,"admin_add.html")

#merchandise page
def product_list(request):
    adminuser=request.session.get("adminuser")
    product_list=models.MerchTable.objects.all()[0:500]#show the first 500 result
    for i in product_list:
        i.Merch_shop_Address = models.ShopTable.objects.get(Shop_id=i.Merch_sid_id).Shop_address#return the merch obejct and the shop address that merch belongs to

    return render(request,"product_list.html",{"adminuser":adminuser,"procuct_list":product_list})

#delete the merchandise
def product_delete(request):
    pk = request.GET.get('pk')
    models.MerchTable.objects.filter(pk=pk).delete()
    return redirect("/product_list/")

# edit the merchandise
def product_edit(request):
    pk = request.GET.get('pk')
    product_data=models.MerchTable.objects.get(pk=pk)
    type_data=product_data.Merch_tag#get the tag
    if request.method=="POST":
        product_data.Merch_name = request.POST.get("Merch_name")
        product_data.Merch_price = request.POST.get("Merch_price")
        product_data.save()#save the edited information

        return redirect("/product_list/")#refresh
    return render(request,"product_edit.html",{"MerchTable":product_data,"type_data":type_data})

#add the new merch
def product_add(request):
    counter = 0
    # print("Step0")
    shop_data = models.ShopTable.objects.all()
    sid = []
    # print("Step1")
    for i in shop_data:# get the shop id to return to user to choose the merchandises' shop
        counter +=1
        if counter >=200:
            break
        sid.append(i.Shop_id)
    # print("Step2")
    if request.method=="POST":
        m = MerchTable()#create the new merchandise object
        m.Merch_id = create_merch_id()#create the merch id
        m.Merch_name = request.POST.get('name')#get the input information
        m.Merch_img = request.POST.get("img")
        m.Merch_tag = request.POST.get("tag")
        m.Merch_price = request.POST.get("price")
        # print("Step2.5")
        sid1 = request.POST.get("temp")
        # print(sid1)
        m.Merch_sid = models.ShopTable.objects.get(Shop_id=sid1)#use foreign key to get the shop object for sid
        # print("Step3")
        # print(m.Merch_id)
        # print(m.Merch_name)
        # print(m.Merch_img)
        # print(m.Merch_tag)
        # print(m.Merch_price)
        # print(m.Merch_sid)
        m.save()#save the object


        return redirect("/product_list/")

    return render(request,"product_add.html",{"sid":sid})

#show the all user
def user_list(request):
    adminuser=request.session.get("adminuser")
    user_list=models.UserTable.objects.all()
    return render(request,"user_list.html",{"user_list":user_list,"adminuser":adminuser})

#edit the user
def user_edit(request):
    pk = request.GET.get('pk')
    user_data = models.UserTable.objects.get(pk=pk)
    if request.method=="POST":
        user_data.User_name = request.POST.get("name")
        user_data.User_address = request.POST.get("address")
        user_data.User_phone=request.POST.get("phone")
        user_data.save()#save th edited information
        return redirect("/user_list/")
    return render(request,"user_edit.html",{"user":user_data})
#
# show the order list
def order_list(request):
    order_list=models.OrderTable.objects.all()
    for i in order_list:#edit the return data
        i.order_id = i.Order_id
        i.order_shop_name = models.ShopTable.objects.get(Shop_id=i.Order_sid_id).Shop_name
        i.order_user_name = models.UserTable.objects.get(User_id=i.Order_uid_id).User_name
        i.order_date = i.Order_date
    return render(request,"order_list.html",{"order_list":order_list})
# cancle the order
def order_del(request):
    pk = request.GET.get('pk')
    models.OrderTable.objects.filter(Order_id=pk).delete()#delete the order
    return redirect("/order_list/")


def create_Admin():#create the admin
    print("Start admin")
    a = admin()
    a.admin_name = "yhs12"
    a.admin_pwd = "12345678"
    a.save()
    print("Done")

# def insert_user():
#
#     for i in range(0,10):
#         u = UserTable()
#         u.User_id = i
#         u.User_psw = str(i*10)
#         u.User_name = str(i*100)
#         u.User_phone = str()


def create_id():#create the user id
    list1 = []
    #u1 = models.UserTable.objects.all()
    if models.UserTable.objects.all():
        print("Not null")
        list1 = []
        u1 = models.UserTable.objects.all()
        for i in u1:
            list1.append(int(i.User_id))
        #print(max(list1)+1)
        return str(max(list1)+1)# get the max id and add one

        print("create_id Done")
    else:#if nothing in user table
        print("Null")
        return "101000001"
    # for i in u1:
    #     list1.append(i.User_id)

def create_merch_id():#create the merchandise id
    if models.MerchTable.objects.all():
        print("Not null")
        list1 = []
        u1 = models.MerchTable.objects.all()
        for i in u1:
            list1.append(int(i.Merch_id))
        #print(max(list1)+1)
        return str(max(list1)+1)# get the max id and add one

        print("create_id Done")
    else:
        print("Null")
        return "20100000000000000000001"

def create_order_id():#create the order id
    if models.OrderTable.objects.all():
        print("Not null")
        list1 = []
        o1 = models.OrderTable.objects.all()
        for i in o1:
            list1.append(int(i.Order_id))
        #print(max(list1)+1)
        return str(max(list1)+1)# get the max id and add one

        print("create_order_id Done")
    else:
        print("Null")
        return "102000001"

def create_phone():
    second = [3, 4, 5, 7, 8][random.randint(0, 4)]

    # third number
    third = {
        3: random.randint(0, 9),
        4: [5, 7, 9][random.randint(0, 2)],
        5: [i for i in range(10) if i != 4][random.randint(0, 8)],
        7: [i for i in range(10) if i not in [4, 9]][random.randint(0, 7)],
        8: random.randint(0, 9),
    }[second]

    # final eight number
    suffix = random.randint(9999999, 100000000)

    # concat
    return "1{}{}{}".format(second, third, suffix)


def insert_shop():#insert the edited shop data into schema
    counter = 0
    result_df = DataProcess.DataCleaning.data_process_return(r'C:\Users\寒升\Desktop\电商网站\phoneShop\DataProcess')#get the return dataframe
    #print(result_df)
    df = result_df.drop_duplicates(["s_id"])#drop the repeat value
    #print(df)
    df2 = start_process()#start edit process
    se1 = joint_address(df2)

    for row in df.iterrows():
        # if counter >=10:
        #     break

        s = ShopTable()
        s.Shop_id = str(list(row[1])[-1])[:-2]# remove the useless string part
        s.Shop_name = list(row[1])[-4]# get the name
        s.Shop_address = return_address(se1)#create a random address
        #print(s.Shop_id)
        #print(s.Shop_name)
        #print(s.Shop_address)
        s.save()#save the shopTable object
        counter +=1
        if counter % 100 == 0:# view the insert process
            print(counter)

    print(counter)#print the shop amount

def insert_merch():#insert the merchandise
    counter = 0
    result_df = DataProcess.DataCleaning.data_process_return(r'C:\Users\寒升\Desktop\电商网站\phoneShop\DataProcess')
    #print(result_df)
    for row in result_df.iterrows():
        # #if counter >= 10:
        # if counter >=2000:
        #     break
        counter += 1
        if counter % 100 == 0:
            print(counter)

        data_list = list(row[1])
        #print(data_list)

        m = MerchTable()
        #s = ShopTable()
        m.Merch_id = data_list[-2]#get the target data from different list position
        m.Merch_name = data_list[3]
        m.Merch_img = data_list[0]
        m.Merch_tag = data_list[2].split("\\")[-1][2:]
        m.Merch_price = data_list[1]
        m.Merch_sid = ShopTable.objects.get(Shop_id = str(data_list[-1])[:-2])
        # print(m.Merch_id)
        # print(m.Merch_name)
        # print(m.Merch_img)
        # print(m.Merch_tag)
        # print(m.Merch_price)
        # print(m.Merch_sid)
        #print(ShopTable.objects.get(Shop_id = str(data_list[-1])[:-2]))
        m.save()#save the MerTable object

    print(counter)#print the merchandise amount


if __name__ == '__main__':
    print("This will start Insert. Do you already done?")
    print("Be Careful!")
    #insert_shop()

    #insert_merch()
    #create_Admin()



